//前端axios默认配置
import router from '@/router'
import axios, { type AxiosInstance } from 'axios'
import variable from '@/utils/properties.yaml'
import { ElMessage } from 'element-plus'

const myAxios: AxiosInstance = axios.create({
  baseURL:
    variable.process.NODE_ENV == 'development'
      ? 'http://localhost:8080'
      : 'http://127.0.0.1:4523/m1/6265905-5960000-default', //区别开发环境和生产环境
  timeout: 10000,
  withCredentials: true, //需要验证
  headers: { 'X-Custom-Header': 'foobar', token: null },
})

// 添加请求拦截器
myAxios.interceptors.request.use(
  function (config) {
    const token: string = localStorage.getItem('token')
    if (token) {
      config.headers.token = token
    }
    console.log('Axios拦截器请求前:', config)
    return config //放行请求
  },
  function (error) {
    // 对请求错误做些什么
    console.error('Axios拦截器请求前出错:', error)
    return Promise.reject(error)
  },
)

myAxios.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。正确的返回
    console.log('Axios拦截器响应前正常返回:', response)
    if (response.data.code != 1) {
      ElMessage.error(response.data.msg)
      return Promise.reject(response.data.msg || '操作失败')
    }
    return response.data //只返回data数据就行
  },
  function (error) {
    //错误代码的返回2xx以外的代码
    //如果有返回,只是有错误
    if (error.response) {
      const status = error.response.status
      const msg = error.response.data.error || '请求失败'
      switch (status) {
        case 404:
          router.push({
            path: '/error',
            params: {
              message: '404 Not Found',
            },
          })
          break
        case 400:
          router.push({
            path: '/error',
            params: {
              message: error.response.data.msg,
            },
          })
        case 401:
          ElMessage.error('登录过期，请重新登录')
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          router.push('/user-login')
          break
        case 403:
          ElMessage.error('无权限访问')
          break
        case 500:
          router.push({
            path: '/error',
            params: {
              message: msg || '服务器内部错误',
            },
            replace: true,
          })
          break
        default:
          ElMessage.error('未知错误:' + status)
      }
    } else if (error.request) {
      ElMessage.error('服务器无响应,请检查网络')
    } else {
      ElMessage.error('未知错误:', error.message)
    }
    console.error('Axios拦截器响应前错误返回:', error)
    return Promise.reject(error)
  },
)

export default myAxios
